package com.atguigui.leetcode1;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 1110.删点成林
 * Project: leetcode
 * Package: com.atguigui.leetcode1
 * Version: 1.0
 * <p>
 * Created by WJX on 2023/5/30 8:53
 */
public class P1110DeleteNodesAndReturnForest {
    public static void main(String[] args) {
        Solution solution = new P1110DeleteNodesAndReturnForest().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
            var ans = new ArrayList<TreeNode>();
            var s = new HashSet<Integer>();
            for (int i : to_delete) {
                s.add(i);
            }
            if (dfs(ans, s, root) != null) ans.add(root);

            return ans;
        }

        private TreeNode dfs(List<TreeNode> ans, Set<Integer> s, TreeNode node) {
            if (node == null) return null;
            node.left = dfs(ans, s, node.left);
            node.right = dfs(ans, s, node.right);
            if (!s.contains(node.val)) return node;
            if (node.left != null) ans.add(node.left);
            if (node.right != null) ans.add(node.right);
            return null;
        }
    }
}
